import { computed, ref, watchEffect } from 'vue';
import { RouteRecordRaw, RouteRecordNormalized } from 'vue-router';
import usePermission from '@/hooks/permission';
import { useAppStore, useMenusStore, useClientMenusStore } from '@/store';
import { appClientRoutes } from '@/router/routes/';
import { cloneDeep } from 'lodash';
// import appClientMenus from '@/router/app-menus';

export default function useMenuTree() {
  const permission = usePermission();
  const appStore = useAppStore();
  const menusStore = useMenusStore();
  const userClientStore = useClientMenusStore();
  // const currChildren = ref(menusStore.currMenus[0].children); // 用来刷新menuTree中的computed的缓存
  const currChildren = ref(); // 用来刷新menuTree中的computed的缓存
  const menuTree = computed(() => {
    // const copyRouter = JSON.parse(JSON.stringify(appRoute.value));

    // 获取pinia里面当前的路由，并取过滤一级路由，就是只需拿到二级路由显示在页面，所以要.children，并且currMenus数组只有一个对象，所以默认currMenus[0]就行了
    const copyRouter = ref();

    // if (window.name == "") {
    //   copyRouter.value = menusStore.currMenus[0].children;
    //   console.log("首次被加载");
    //   window.name = "isReload"; // 在首次进入页面时我们可以给window.name设置一个固定值
    // } else if (window.name == "isReload") {
    //   console.log("页面被刷新");
    // }

    // 每次赋值刷新缓存，如果不刷新缓存则路由菜单不会变化
    currChildren.value = menusStore.currMenus;
    // menusStore.currMenus[0].children  Math.random();

    if (localStorage.getItem('userRole') === 'admin') {
      if (sessionStorage.getItem('currMenus')) {
        copyRouter.value = JSON.parse(
          sessionStorage.getItem('currMenus') as any
        ).children;
        // menusStore.currMenus = JSON.parse(sessionStorage.getItem('currMenus') as any).children;
      } else {
        copyRouter.value = menusStore.currMenus[0].children;
      }
    } else {
      copyRouter.value = cloneDeep(appClientRoutes) as RouteRecordNormalized[];
    }

    copyRouter.value?.sort(
      (a: RouteRecordNormalized, b: RouteRecordNormalized) => {
        return (a.meta.order || 0) - (b.meta.order || 0);
      }
    );
    function travel(_routes: RouteRecordRaw[], layer: number) {
      if (!_routes) return null;

      const collector: any = _routes.map((element) => {
        // no access
        if (!permission.accessRouter(element)) {
          return null;
        }

        // leaf node 判断有没有子路由
        if (element.meta?.hideChildrenInMenu || !element.children) {
          element.children = [];
          return element;
        }

        // route filter hideInMenu true  判断有没有路由hideInMenu为true
        element.children = element.children.filter(
          (x) => x.meta?.hideInMenu !== true
        );

        // Associated child node 关联的子节点
        const subItem = travel(element.children, layer + 1);

        if (subItem.length) {
          element.children = subItem;
          return element;
        }
        // the else logic
        if (layer > 1) {
          element.children = subItem;
          return element;
        }

        if (element.meta?.hideInMenu === false) {
          return element;
        }

        return null;
      });
      return collector.filter(Boolean);
    }
    return travel(copyRouter.value as any, 0);
  });

  return {
    menuTree
  };
}
